<template>
  <v-container fluid fill-height class="login-container">
    <v-layout class="align-center justify-center">
      <v-flex xs12 sm8 md6 lg5 xl3>
        <v-card class="elevation-12">
          <v-toolbar color="primary" dark flat src="../../assets/img/login/vbanner.jpg">
            <v-toolbar-title>用户登录</v-toolbar-title>
            <template v-slot:extension>
              <v-tabs v-model="currentTab">
                <v-tabs-slider color="yellow" />
                <v-tab>个人登录</v-tab>
                <v-tab>政企登录</v-tab>
              </v-tabs>
            </template>
          </v-toolbar>
          <v-tabs-items v-model="currentTab">
            <v-tab-item>
              <v-card flat>
                <v-card-text>
                  <v-form ref="personal_login_form">
                    <v-text-field
                      v-model="personalForm.phoneNumber"
                      label="手机号码"
                      name="phoneNumber"
                      prepend-icon="mdi-phone-dial"
                      type="text"
                      :rules="[rules.required, rules.phoneNumber]"
                      @keyup="handleVerificationCodeBtn"
                    >
                      <v-btn
                        slot="append"
                        :plain="sendVerificationCodeDisabled"
                        :disabled="sendVerificationCodeDisabled"
                        :loading="sendVerificationCodeLoading"
                        @click="sendVerificationCode"
                        v-text="sendVerificationCodeBtnText"
                      />
                    </v-text-field>
                    <v-text-field
                      v-model="personalForm.verificationCode"
                      label="短信验证码"
                      name="verificationCode"
                      prepend-icon="mdi-phone-message"
                      type="text"
                      :rules="[rules.required, rules.verificationCode]"
                    />
                  </v-form>
                </v-card-text>
                <v-card-actions>
                  <v-spacer />
                  <v-btn
                    :loading="personalLoginLoading"
                    color="primary"
                    @click="personalLogin"
                  >登录</v-btn>
                </v-card-actions>
              </v-card>
            </v-tab-item>
            <v-tab-item>
              <v-card flat>
                <v-card-text>
                  <v-form ref="government_enterprise_login_form">
                    <v-text-field
                      v-model="governmentEnterpriseForm.email"
                      label="email"
                      name="email"
                      prepend-icon="mdi-at"
                      type="text"
                      :rules="[rules.required, rules.email]"
                    />
                    <v-text-field
                      v-model="governmentEnterpriseForm.password"
                      label="密码"
                      name="password"
                      prepend-icon="mdi-lock"
                      :type="passwordDisplay ? 'text' : 'password'"
                      :append-icon="passwordDisplay ? 'mdi-eye' : 'mdi-eye-off'"
                      :rules="[rules.required, rules.password]"
                      @click:append="passwordDisplay = !passwordDisplay"
                    />
                  </v-form>
                </v-card-text>
                <v-card-actions>
                  <v-spacer />
                  <v-btn
                    :loading="governmentEnterpriseLoginLoading"
                    color="primary"
                    @click="governmentEnterpriseLogin"
                  >登录</v-btn>
                </v-card-actions>
              </v-card>
            </v-tab-item>
          </v-tabs-items>
          <v-footer padless class="login-footer">
            <v-col
              class="text-center register-tip-wrapper"
              cols="12"
            >
              <v-btn plain><v-icon left>mdi-account-plus</v-icon>新用户注册</v-btn>
              <v-btn plain><v-icon left>mdi-lock-question</v-icon>忘记密码</v-btn>
            </v-col>
            <v-col cols="12">
              <v-divider />
            </v-col>
            <v-col
              class="text-center text-caption"
              cols="12"
            >
              Copyright © 2021 All rights reserved
            </v-col>
          </v-footer>
        </v-card>
      </v-flex>
    </v-layout>
  </v-container>
</template>

<script>
import { sendVerificationCode } from '@/api/sms'
export default {
  name: 'Login',
  data: () => ({
    currentTab: '',
    passwordDisplay: false,
    personalLoginLoading: false,
    governmentEnterpriseLoginLoading: false,
    personalForm: {
      phoneNumber: '18308748310',
      verificationCode: '123456'
    },
    governmentEnterpriseForm: {
      email: 'ivup@ivup.cn',
      password: 'a1234567'
    },
    sendVerificationCodeDisabled: true,
    sendVerificationCodeBtnText: '发送验证码',
    sendVerificationCodeLoading: false,
    sendVerificationCodeTime: 0,
    sendVerificationCodeTimer: null,
    rules: {
      required: value => !!value || '必填项，此项不能为空',
      phoneNumber: value => /^13[\d]{9}$|^14[5,7]{1}\d{8}$|^15[^4]{1}\d{8}$|^17[\d]{9}$|^18[\d]{9}$|^19[\d]{9}$/.test(value) || '手机号码格式无效',
      verificationCode: value => /^[0-9]{6}$/.test(value) || '短信验证码必须为6位数字',
      email: value => /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,6})$/.test(value) || 'email地址格式无效',
      password: value => new RegExp('^(?![a-zA-Z]+$)(?![0-9]+$)[a-zA-Z0-9]{8,16}$').test(value) || '密码中必须包含字母、数字，至少8个字符，最多16个字符'
    }
  }),
  mounted() {
    this.handleVerificationCodeBtn()
  },
  methods: {
    governmentEnterpriseLogin() {
      if (!this.$refs.government_enterprise_login_form.validate()) return
      // 表单验证成功
      this.governmentEnterpriseLoginLoading = true
      this.$store.dispatch('user/governmentEnterpriseLogin', this.governmentEnterpriseForm).then(() => {
        this.governmentEnterpriseLoginLoading = false
        this.$router.replace('/')
      }).catch(error => {
        this.$message.error(error)
      }).finally(() => {
        this.governmentEnterpriseLoginLoading = false
      })
    },
    personalLogin() {
      if (!this.$refs.personal_login_form.validate()) return
      // 表单验证成功
      this.personalLoginLoading = true
      this.$store.dispatch('user/personalLogin', this.personalForm).then(() => {
        this.personalLoginLoading = false
        this.$router.replace('/')
      }).catch(error => {
        this.$message.error(error)
      }).finally(() => {
        this.personalLoginLoading = false
      })
    },
    handleVerificationCodeBtn() {
      if (/^13[\d]{9}$|^14[5,7]{1}\d{8}$|^15[^4]{1}\d{8}$|^17[\d]{9}$|^18[\d]{9}$|^19[\d]{9}$/.test(this.personalForm.phoneNumber)) {
        this.sendVerificationCodeDisabled = false
      } else {
        this.sendVerificationCodeDisabled = true
      }
    },
    sendVerificationCode() {
      this.sendVerificationCodeLoading = true
      sendVerificationCode('login', this.personalForm.phoneNumber).then(() => {
        this.sendVerificationCodeLoading = false
        this.$message.success('验证码发送成功')
        const TIME_COUNT = 60
        if (this.sendVerificationCodeTimer === null) {
          this.sendVerificationCodeTime = TIME_COUNT
          this.sendVerificationCodeBtnText = TIME_COUNT + 's后重新获取'
          this.sendVerificationCodeDisabled = true
          this.sendVerificationCodeTimer = setInterval(() => {
            if (this.sendVerificationCodeTime > 0 && this.sendVerificationCodeTime <= TIME_COUNT) {
              this.sendVerificationCodeTime--
              this.sendVerificationCodeBtnText = this.sendVerificationCodeTime + 's后重新获取'
            } else {
              this.sendVerificationCodeDisabled = false
              clearInterval(this.sendVerificationCodeTimer)
              this.sendVerificationCodeTimer = null
              this.sendVerificationCodeBtnText = '发送验证码'
            }
          }, 1000)
        }
      }).catch(error => {
        this.$message.error(error)
      }).finally(() => {
        this.sendVerificationCodeLoading = false
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.login-container {
  background-image: url(../../assets/img/login/bg.jpg);
  background-position: center;
  background-size: cover;
  background-repeat: no-repeat;
  .login-footer {
    margin-top: 30px;
    .register-tip-wrapper {
      margin-top: 30px;
    }
  }
}
</style>
